// pages/role-select/role-select.js
const app = getApp()
const api = require('../../utils/api.js')

Page({
    data: {
        selectedRole: '',
        teacherId: '',
        submitting: false
    },

    // 选择角色
    selectRole(e) {
        const role = e.currentTarget.dataset.role
        this.setData({ selectedRole: role })
    },

    // 输入教师工号
    onTeacherIdInput(e) {
        this.setData({ teacherId: e.detail.value })
    },

    // 提交角色选择
    async submitRole() {
        if (!this.data.selectedRole) {
            wx.showToast({
                title: '请选择身份',
                icon: 'none'
            })
            return
        }

        if (this.data.selectedRole === 'student' && !this.data.teacherId.trim()) {
            wx.showToast({
                title: '请输入指导教师工号',
                icon: 'none'
            })
            return
        }

        if (this.data.submitting) return

        this.setData({ submitting: true })
        wx.showLoading({ title: '提交中...' })

        try {
            await api.setUserRole({
                openid: app.globalData.openid,
                role: this.data.selectedRole,
                teacherId: this.data.selectedRole === 'student' ? this.data.teacherId : null
            })

            // 保存角色信息到全局
            app.globalData.userRole = this.data.selectedRole

            wx.hideLoading()
            wx.showToast({
                title: '设置成功',
                icon: 'success',
                duration: 2000
            })

            // 跳转到首页
            setTimeout(() => {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }, 2000)

        } catch (error) {
            wx.hideLoading()
            console.error('设置角色失败:', error)
            wx.showToast({
                title: error.message || '设置失败',
                icon: 'none'
            })
        } finally {
            this.setData({ submitting: false })
        }
    }
})
